import { useEffect, useRef, useState } from 'react';
import { admin_list, admin_role, admin_user_role, create_admin_user, delete_admin_user, update_admin_user, user_wechat_bind } from '@/services/admin/user/user';
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import type { ProColumnType, ActionType } from '@ant-design/pro-table';
import { Button, Card, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ProForm, { ProFormText, ProFormSwitch, ProFormTextArea, ProFormCheckbox } from '@ant-design/pro-form'
import { Link } from 'react-router-dom';
import { Popconfirm, Tooltip } from 'antd';
import Qrcode from '@/pages/components/Qrcode';


export default function Page() {
  const actionRef = useRef<ActionType>();
  // 管理员修改modal
  const [EditModalVisible, setEditModalVisible] = useState(false)
  // 管理员创建modal
  const [userAddModalVisible, setuserAddModalVisible] = useState(false)
  // 管理员微信换绑定
  const [BindModalVisible, setBindModalVisible] = useState(false)
  // 当前管理员拥有的角色
  const [serviceroles, setserviceroles] = useState<UserResponse.AdminRoles[] | []>([])
  // 指定管理员拥有的角色
  const [userroles, setuserroles]: [any, any] = useState([])
  // 当前操作的管理员
  const [onuser, setonuser] = useState<User.UserData>()
  // 当前管理员微信换绑链接
  const [url, seturl] = useState("")

  const [expires, setexpires] = useState(0)
  /**
   * 获取当前管理员拥有的角色
   */
  const get_admin_roles = async () => {
    // 获取当前管理员拥有的角色
    const res = await admin_role();
    if (res.code === 200) {
      setserviceroles(res.data)
    } else {
      message.info(res.message)
    }
  }
  /**
   * 管理员启用
   * @param d 
   */
  const userEnable = async (d: User.UserData) => {
    const res = await update_admin_user({ user_id: d.id, full_name: d.full_name, u_status: 1, roles: [] })
    if (res.code === 200) {
      actionRef.current?.reload()
      message.success(res.message)
    } else {
      message.info(res.message)
    }
  }
  /**
   * 删除管理员
   * @param d 
   */
  const userDelete = async (d: User.UserData) => {
    const res = await delete_admin_user({ user_id: d.id })
    if (res.code === 200) {
      actionRef.current?.reload()
      message.success(res.message)
    } else {
      message.info(res.message)
    }
  }

  /**
   * 管理员禁用
   * @param d 
   */
  const userDisabled = async (d: User.UserData) => {
    const res = await update_admin_user({ user_id: d.id, full_name: d.full_name, u_status: 2, roles: [] })
    if (res.code === 200) {
      actionRef.current?.reload()
      message.success(res.message)
    } else {
      message.info(res.message)
    }
  }
  /**
   * 管理员修改窗口
   */
  const editAdmin = async (d: User.UserData) => {
    setonuser(d)
    // 获取管理员对应角色
    const admin_roles = await admin_user_role({ user_id: d.id })
    if (admin_roles.code === 200) {
      // 获取指定管理员已有角色
      const myroles = admin_roles.data.map((r: UserResponse.AdminRoles) => {
        if (r.checked) {
          return r.value
        }
        return null
      })
      // 设置用户已有角色
      setuserroles(myroles)
      // 弹开编辑窗口
      setEditModalVisible(!EditModalVisible)
    } else {
      // 获取失败
      message.info(admin_roles.message)
    }

  }
  /**
   * 管理员更新
   * @param v AdminForm
   */
  const updateAdmin = async (v: User.AdminForm) => {
    const res = await update_admin_user({ user_id: onuser?.id, ...v })
    if (res.code === 200) {
      actionRef.current?.reload()
      message.success(res.message)
      setEditModalVisible(!EditModalVisible)
    } else {
      message.info(res.message)
    }
  }
  /**
   * 管理员添加窗口
   */
  const addadmin = async () => {
    // 打开添加窗口
    setuserAddModalVisible(!userAddModalVisible)
  }
  /**
   * 创建管理员
   * @param values User.AdminForm
   */
  const createAdmin = async (values: User.AdminForm) => {
    if (values) {
      const res = await create_admin_user(values)
      if (res.code === 200) {
        actionRef.current?.reload()
        message.success("创建成功")
        setuserAddModalVisible(false)
      } else {
        message.info(res.message)
      }
    }
  }

  // 管理员换绑微信
  const bind_user = async (d: User.UserData) => {
    const res = await user_wechat_bind({ uid: d.id })
    if (res.code === 200) {
      seturl(res.data.qrcode_url)
      setexpires(res.data.expires_time / 60)
      setBindModalVisible(!BindModalVisible)
    } else {
      message.info(res.message)
    }
  }

  const Export = () => {
    message.info("开发中...")
  }

  useEffect(() => {
    get_admin_roles()
    return () => {
    }
  }, [])

  const Columns: ProColumnType<User.UserData>[] = [
    { title: "头像", dataIndex: "headimgurl", width: 50, valueType: "avatar", hideInSearch: true },
    {
      title: "姓名", dataIndex: "full_name", valueType: "text",
      formItemProps: {
        rules: [
          { pattern: /^[\u4E00-\u9FA5]{2,}/, message: "请输入中文姓名" }
        ]
      }
    },
    { title: "昵称", dataIndex: "nickname", valueType: "text", hideInSearch: true },
    { title: "备注", dataIndex: "remarks", valueType: "text", hideInSearch: true },
    {
      title: "手机号", dataIndex: "u_phone", width: 150, valueType: "text", copyable: true,
      formItemProps: {
        rules: [
          { pattern: /^1[34567890]\d{9}/, message: "请填写正确的手机号" },
        ],

      }
    },
    { title: "创建时间", dataIndex: "create_time", width: 150, valueType: "dateTime", hideInSearch: true },
    { title: "创建时间", dataIndex: "create_time", valueType: "dateTimeRange", hideInTable: true },
    { title: "更新时间", dataIndex: "update_time", width: 150, valueType: "dateTime", hideInSearch: true },
    {
      title: "用户状态",
      dataIndex: "u_status",
      hideInSearch: true,
      width: 80,
      valueEnum: {
        1: { text: '已启用', status: 'Success' },
        2: { text: '已禁用', status: 'Error' },
        0: { text: '未激活', status: 'Default' }
      },
      order: 1
    },
    {
      title: "操作", fixed: 'right', valueType: "option", render: (r, d) => [
        <Tooltip key={"tipbind"} placement="topLeft" title={"更换管理员微信"}>
          <Button key={"tipbind"} size="small" type="dashed" onClick={async () => bind_user(d)}>更换</Button>
        </Tooltip>,
        <Tooltip key={"tipenable"} placement="topLeft" title={"启用管理员"}>
          <Button key="enabel" size="small" onClick={async () => {
            await userEnable(d)
          }} hidden={!(d.u_status === 0 || d.u_status === 2)} disabled={d.type} type="primary">启用</Button>
        </Tooltip>,
        <Tooltip key={"tipdisable"} placement="topLeft" title={"禁用管理员"}>
          <Button key="disabel" size="small" onClick={async () => {
            await userDisabled(d)
          }} hidden={(d.u_status !== 1)} disabled={d.type} danger>禁用</Button></Tooltip>,
        <Tooltip key={"tipedit"} placement="topLeft" title={"编辑管理员"}>
          <Button key="edit" size="small" onClick={async () => { await editAdmin(d) }}>编辑</Button>
        </Tooltip>,
        <Tooltip key={"tipdel"} placement="topLeft" title={"删除管理员"}>
          <Popconfirm key={d.id} placement="topLeft" title={`确定删除 ${d.full_name} 管理员吗`} onConfirm={async () => { await userDelete(d) }}
            okText="Yes"
            cancelText="No"
          >
            <Button key="deleteuser" size="small" disabled={d.type} danger>删除</Button>
          </Popconfirm>
        </Tooltip>,
      ]
    },
  ]

  return (
    <PageContainer breadcrumb={undefined}>
      <Card>
        <ProTable
          actionRef={actionRef}
          columns={Columns}
          scroll={{ x: 1400 }}
          size="small"
          pagination={{ pageSize: 10 }}
          request={async (params: User.QueryForm) => {
            return await admin_list(params)
          }}
          form={{ ignoreRules: false }}
          search={{
            defaultCollapsed: true,
            labelWidth: 'auto',
            optionRender: ({ searchText, resetText }, { form }) => {
              return [
                <Button
                  key="searchText"
                  type="primary"
                  onClick={() => {
                    form?.submit();
                  }}
                >
                  {searchText}
                </Button>,
                <Button
                  key="resetText"
                  onClick={() => {
                    form?.resetFields();
                  }}
                >
                  {resetText}
                </Button>,
                <Button key="out" onClick={Export}>导出</Button>,
              ];
            },
          }}
          toolBarRender={() => [
            <Button key="add_user" type="primary" onClick={addadmin}>
              <PlusOutlined />
            添加管理员
          </Button>,
          ]}
        // 多选操作
        // rowSelection={{ selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT] }}
        >
        </ProTable>
      </Card>
      <Modal
        title="创建管理员"
        visible={userAddModalVisible}
        onCancel={() => { setuserAddModalVisible(!userAddModalVisible) }}
        footer={false}
        destroyOnClose={true}
      >
        <ProForm
          onFinish={createAdmin}
          submitter={{ searchConfig: { submitText: "创建" } }}
        >
          <ProForm.Item label="姓名">
            <ProFormText name="full_name"
              rules={[
                { required: true, message: "请输入管理员姓名" },
                { pattern: /^[\u4E00-\u9FA5]{2,}$/, message: "姓名为中文至少2个字符" }
              ]}
            ></ProFormText>
          </ProForm.Item>
          <ProForm.Item label="备注">
            <ProFormTextArea
              name="remarks"
              fieldProps={{ maxLength: 30, showCount: true }}
              rules={[
                { max: 30, message: "备注长度输入30个字符以内" }
              ]}
            ></ProFormTextArea>
          </ProForm.Item>
          <ProForm.Item>
            <ProFormSwitch
              label="启用状态"
              name="u_status"
              initialValue={true}
              checkedChildren="开启"
              unCheckedChildren='关闭'
            ></ProFormSwitch>
          </ProForm.Item>
          <h5 hidden={serviceroles.length > 0}>未创建角色 <Link to="/admin/role">去创建一个？</Link> </h5>
          <ProFormCheckbox.Group
            name="roles"
            // layout="vertical"
            label="角色"
            options={serviceroles}
            initialValue={[]}
          />

        </ProForm>
      </Modal>
      <Modal
        title="编辑管理员"
        visible={EditModalVisible}
        onCancel={() => { setEditModalVisible(!EditModalVisible) }}
        footer={false}
        destroyOnClose={true}
      >
        <ProForm
          onFinish={updateAdmin}
          submitter={{ searchConfig: { submitText: "更新" }, resetButtonProps: { hidden: true } }}
        >
          <ProForm.Item label="姓名">
            <ProFormText name="full_name"
              initialValue={onuser?.full_name}
              rules={[
                { required: true, message: "请输入管理员姓名" },
                { pattern: /^[\u4E00-\u9FA5]{2,}$/, message: "姓名为中文至少2个字符" }
              ]}
            ></ProFormText>
          </ProForm.Item>
          <ProForm.Item label="备注">
            <ProFormTextArea
              initialValue={onuser?.remarks}
              fieldProps={{ maxLength: 30, showCount: true }}
              name="remarks"
              rules={[
                { max: 30, message: "备注长度输入30个字符以内" }
              ]}
            ></ProFormTextArea>
          </ProForm.Item>
          <ProForm.Item>
            <ProFormSwitch
              label="启用状态"
              name="u_status"
              initialValue={(onuser?.u_status) === 1}
              checkedChildren="开启"
              unCheckedChildren='关闭'
            ></ProFormSwitch>
          </ProForm.Item>
          <h5 hidden={serviceroles.length > 0}>未创建角色 <Link to="/admin/role">去创建一个？</Link> </h5>
          <ProFormCheckbox.Group
            name="roles"
            // layout="vertical"
            label="角色"
            options={serviceroles}
            initialValue={userroles}
          />
        </ProForm>
      </Modal>
      <Modal
        title="管理员微信更换"
        visible={BindModalVisible}
        onCancel={() => { setBindModalVisible(!BindModalVisible); actionRef.current?.reload() }}
        footer={false}
        destroyOnClose={true}
        width={300}
      >
        <div style={{ display: "flex", justifyContent: "center", flexFlow: "column"}}>
          <div style={{ display: "flex", justifyContent: "center",}}>
            <Qrcode url={url} desc="管理员扫码" size={192} />
          </div>
          <div style={{ display: "flex", justifyContent: "center", color: "red"}}>
            <span>请在 {expires} 分钟内扫码绑定</span>
          </div>
        </div>
      </Modal>
    </PageContainer>
  );
}

